<template>
  <div class="app-container">
    <el-form :inline="true" :model="searchFormData" class="demo-form-inline">
      <el-form-item label="AppId">
        <el-input v-model="searchFormData.appKey" :clearable="true" placeholder="AppId" style="width: 250px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="onSearchTable">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary"  icon="Plus" style="margin-bottom: 10px;" @click="onAdd">新增ISV</el-button>
    <el-table
      :data="pageInfo.list"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        prop="appKey"
        label="AppId"
        width="250"
      />
      <el-table-column
        prop=""
        label="秘钥"
        width="80"
      >
        <template #default="scope">
          <el-button type="info" text  @click="onShowKeys(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="roleList"
        label="角色"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span v-html="roleRender(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column
        prop="userId"
        label="注册用户"
        width="100"
      >
        <template #header>
          注册用户
          <el-tooltip content="注册用户自行管理秘钥" placement="top">
            <i class="el-icon-question" style="cursor: pointer"></i>
          </el-tooltip>
        </template>
        <template #default="scope">
          <span v-if="scope.row.userId" style="font-weight: bold;">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="80"
      >
        <template #default="scope">
          <span v-if="scope.row.status === 1" style="color:#67C23A">启用</span>
          <span v-if="scope.row.status === 2" style="color:#F56C6C">禁用</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="gmtCreate"
        label="添加时间"
        width="160"
      />
      <el-table-column
        prop="remark"
        label="备注"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        width="200"
      >
        <template #default="scope">
          <el-button type="info" text  @click="onTableUpdate(scope.row)">修改</el-button>
          <el-button v-if="!scope.row.userId" type="info" text  @click="onKeysUpdate(scope.row)">秘钥管理</el-button>
          <el-button v-if="!scope.row.userId" type="info" text  @click="onExportKeys(scope.row)">导出秘钥</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      style="margin-top: 5px"
      :current-page="searchFormData.pageIndex"
      :page-size="searchFormData.pageSize"
      :page-sizes="[5, 10, 20, 40]"
      :total="pageInfo.total"
      layout="total, sizes, prev, pager, next"
      @size-change="onSizeChange"
      @current-change="onPageIndexChange"
    />
    <!-- dialog -->
    <el-dialog
      :title="isvDialogTitle"
      v-model="isvDialogVisible"
      :close-on-click-modal="false"
      @close="onIsvDialogClose"
    >
      <el-form
        ref="isvForm"
        :rules="rulesIsvForm"
        :model="isvDialogFormData"
        label-width="120px"

      >
        <el-form-item label="appId">
          <span v-if="isvDialogFormData.id === 0" style="color: gray;">(系统自动生成)</span>
          <span v-else>{{ isvDialogFormData.appKey }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group v-model="isvDialogFormData.roleCode">
            <el-checkbox v-for="item in roles" :key="item.roleCode" :value="item.roleCode">{{ item.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="isvDialogFormData.remark" type="textarea" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="isvDialogFormData.status">
            <el-radio :value="1" name="status">启用</el-radio>
            <el-radio :value="2" name="status">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isvDialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="isSaveButtonDisabled" @click="onIsvDialogSave">保 存</el-button>
      </div>
    </el-dialog>
    <!--view keys dialog-->
    <el-dialog
      title="秘钥信息"
      v-model="isvKeysDialogVisible"
      @close="resetForm(isvKeysFrom)"
    >
      <el-form
        ref="isvKeysFrom"
        :model="isvKeysFormData"
        label-width="160px"

        class="key-view"
      >
        <el-form-item label="appId">
          <span>{{ isvKeysFormData.appKey }}</span>
        </el-form-item>
        <el-form-item v-show="showKeys()" label="秘钥格式">
          <span v-if="isvKeysFormData.keyFormat === 1">PKCS8(JAVA适用)</span>
          <span v-if="isvKeysFormData.keyFormat === 2">PKCS1(非JAVA适用)</span>
        </el-form-item>
        <el-form-item v-show="isvKeysFormData.signType === 2" label="secret">
          <span>{{ isvKeysFormData.secret }}</span>
        </el-form-item>
        <el-tabs v-show="showKeys()" v-model="activeName" type="card" class="keyTabs">
          <el-tab-pane label="ISV公私钥" name="first">
            <el-form-item label="ISV公钥">
              <el-input v-model="isvKeysFormData.publicKeyIsv" type="textarea" placeholder="未上传" readonly />
            </el-form-item>
            <el-form-item v-show="isvKeysFormData.userId === 0" label="ISV私钥">
              <el-input v-model="isvKeysFormData.privateKeyIsv" type="textarea" readonly />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="平台公私钥" name="second">
            <el-form-item label="平台公钥">
              <el-input v-model="isvKeysFormData.publicKeyPlatform" type="textarea" readonly />
            </el-form-item>
            <el-form-item prop="privateKeyPlatform" label="平台私钥">
              <el-input v-model="isvKeysFormData.privateKeyPlatform" type="textarea" readonly />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isvKeysDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style>
  .gen-key {margin-bottom: 0px !important;}
  fieldset {border: 1px solid #ccc; color: gray;margin-left: 40px;margin-bottom: 20px;}
  fieldset label {width: 110px !important;}
  fieldset .el-form-item__content {margin-left: 110px !important;}
  .key-view .el-form-item {margin-bottom: 10px !important;}
  .keyTabs .el-tabs__header{margin-left: 70px;}
</style>
<script setup>
import { ref, reactive, onMounted, watch,nextTick } from 'vue'
import {useRoute,useRouter} from 'vue-router'
import request from '@/utils/request'
import {useMessage} from '@/hooks/message'
const router=useRouter();
const searchFormData=reactive({
    appKey: '',
    pageIndex: 1,
    pageSize: 10
  })
const pageInfo=reactive({
    list: [],
    total: 0
  })
const roles=ref([])
const isvDialogVisible=ref(false)
const isvDialogTitle=ref('新增ISV')
const isvForm=ref();
const isvDialogFormData=reactive({
    id: 0,
    status: 1,
    remark: '',
    roleCode: []
  })
const rulesIsvForm=reactive({
    remark: [
      { min: 0, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
    ]
  })
const activeName=ref('first')
const isSaveButtonDisabled=ref(false)
const isvKeysDialogVisible=ref(false)
const isvKeysForm=ref()
const isvKeysFormData=reactive({
    appKey: '',
    secret: '',
    publicKeyIsv: '',
    privateKeyIsv: '',
    publicKeyPlatform: '',
    privateKeyPlatform: '',
    signType: '',
    userId: 0
  });
const loadTable= async ()=>{
  const resp=await request('/api/isv/info/page', searchFormData)
  Object.assign(pageInfo, resp.data);
  console.log(pageInfo);
}
const loadRouteRole=async()=>{
    if (roles.value.length !== 0) {
      return;
    }
    const resp=await request('/api/role/listAll', {})
    roles.value = resp.data
    console.log(roles);
  }
const onShowKeys=async(row)=> {
    const resp=await request('/api/isv/keys/get', { appKey: row.appKey})
    isvKeysDialogVisible.value = true
    nextTick(() => {
      Object.assign(isvKeysFormData, resp.data)
      isvKeysFormData.userId = row.userId
    })
  }
const onSearchTable=()=> {
    loadTable()
  }
const onTableUpdate=async(row)=> {
    isvDialogTitle.value = '修改ISV'
    isvDialogVisible.value = true
    await nextTick()
    const resp= await request('/api/isv/info/get', { id: row.id })
    const isvInfo = resp.data
    const roleList = isvInfo.roleList
    const roleCode = []
    for (let i = 0; i < roleList.length; i++) {
      roleCode.push(roleList[i].roleCode)
    }
    isvInfo.roleCode = roleCode
    Object.assign(this.isvDialogFormData, isvInfo)
  }
const onKeysUpdate=function(row) {
      router.push({ path: `keys?appKey=${row.appKey}` })
    }
const onExportKeys=async (row)=> {
      await request('isv.keys.get', { appKey: row.appKey }, function(resp) {
        const data = resp.data
        const appId = data.appKey
        const privateKeyIsv = data.privateKeyIsv
        const publicKeyPlatform = data.publicKeyPlatform
        let content = `AppId：${appId}\n\n开发者私钥：\n${privateKeyIsv}\n\n`
        if (publicKeyPlatform) {
          content = content + `平台公钥：\n${publicKeyPlatform}`
        }
        const filename = `${appId}.txt`
        this.downloadText(filename, content)
      })
    }
const onSizeChange=async(size)=> {
      searchFormData.pageSize = size
      loadTable()
    }
const onPageIndexChange=(pageIndex) =>{
      searchFormData.pageIndex = pageIndex
      loadTable()
    }
const onAdd=async()=> {
      isvDialogTitle.value = '新增ISV'
      isvDialogVisible.value = true
      nextTick(() => {
        isvDialogFormData.id = 0
      })
    }
const onIsvDialogSave=()=> {
      isvForm.value.validate(async(valid) => {
        if (valid) {
          isSaveButtonDisabled.value = true
          const uri = isvDialogFormData.id === 0 ? '/api/isv/info/add' : '/api/isv/info/update'
          await request(uri, isvDialogFormData)
          isvDialogVisible.value = false
          loadTable()
        }
      })
    }
const onIsvDialogClose=()=> {
      isvForm.value.resetFields();
      isSaveButtonDisabled.value= false
      isvDialogFormData.status = 1
      isvDialogFormData.roleCode = []
    }
const roleRender=(row)=> {
    if(!row.roleList){
      return null
    }
    const html = []
    const roleList = row.roleList
    for (let i = 0; i < roleList.length; i++) {
      html.push(roleList[i].roleName)
    }
    return html.join(', ')
  }
const showKeys=async() =>{
    return isvKeysFormData.signType === 1
  }
const resetForm=(formEl)=>{
  if(!formEl){
    return;
  }
  formEl.resetFields();
}
onMounted(()=>{
  loadTable()
  loadRouteRole()
})
</script>
